package com.aigao.golf.management.user.controller.organization;

import com.aigao.golf.Utils.DaoUtil;
import com.aigao.golf.Utils.PasswordUtil;
import com.aigao.golf.common.base.PageController;
import com.aigao.golf.common.permissions.DefaultRoles;
import com.aigao.golf.common.permissions.PermissOpt;
import com.aigao.golf.common.permissions.PermissionType;
import com.aigao.golf.common.permissions.ReqPermission;
import com.aigao.golf.common.result.ResultEnum;
import com.aigao.golf.common.result.ResultTo;
import com.aigao.golf.management.user.model.GlUser;
import com.github.pagehelper.StringUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @author QiangHe
 * @date 2018/1/11 21:30
 */
@RestController
@RequestMapping("/group/user")
public class UserController extends PageController<GlUser> {

    @ReqPermission(type = PermissionType.GROUP_USER, opt = PermissOpt.READ)
    @PostMapping("/list")
    public ResultTo list(String id, Integer pageStart, Integer pageLength, String pageOrder) {
        Map<String, Object> param = new HashMap<>(2);
        param.put("creator", id);
        param.put("flag", 0);
        return dataPage(pageStart, pageLength, pageOrder, param);
    }

    /**
     * 添加人员
     *
     * @return
     */
    @ReqPermission(type = PermissionType.GROUP_USER, opt = PermissOpt.WRITE)
    @PostMapping("/add")
    public ResultTo add(@RequestParam("username") String username,
                        @RequestParam("password") String password,
                        @RequestParam("cname") String cname,
                        @RequestParam("org_id") String orgId,
                        @RequestParam("phone") String phone,
                        @RequestParam(name = "authorization_code", required = false) String authorizationCode) {
        GlUser user = new GlUser();
        user.setUsername(username);
        user.setCname(cname);
        user.setOrgId(orgId);
        user.setPhone(phone);
        String salt = UUID.randomUUID().toString();
        user.setPassword(PasswordUtil.encryptPassword(password, salt));
        user.setSalt(salt);
        user.setCreateTime(new Date());
        user.setAuthorizationCode(authorizationCode);
        Subject subject = SecurityUtils.getSubject();
        if (subject != null) {
            GlUser manager = (GlUser) subject.getPrincipal();
            user.setCreator(manager.getId());
        }
        int status = adaptService.insertSelective(user);
        if (status == 1) {
            return new ResultTo(user);
        } else {
            return new ResultTo(ResultEnum.OPERATION_FAILED, "保存失败");
        }
    }

    /**
     * 更新用户
     *
     * @param id 用户ID
     * @return
     */
    @ReqPermission(type = PermissionType.GROUP_USER, opt = PermissOpt.UPDATE)
    @PostMapping("/update")
    public ResultTo update(String id,
                           @RequestParam(name = "username", required = false) String username,
                           @RequestParam(name = "password", required = false) String password,
                           @RequestParam(name = "cname", required = false) String cname,
                           @RequestParam(name = "org_id", required = false) String orgId,
                           @RequestParam(name = "phone", required = false) String phone
    ) {
        Example example = new Example(GlUser.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("id", id);
        GlUser user = new GlUser();
        user.setUsername(username);
        user.setId(id);
        user.setCname(cname);
        user.setOrgId(orgId);
        user.setPhone(phone);
        if (null != password) {
            String salt = UUID.randomUUID().toString();
            user.setPassword(PasswordUtil.encryptPassword(password, salt));
            user.setSalt(salt);
        }
        if (username != null || orgId != null || password != null || phone != null) {
            user.setUpdateTime(new Date());
        }
        if (adaptService.updateByExampleSelective(user, example) == 1) {
            return new ResultTo(ResultEnum.SUCCESS, "更新成功");
        } else {
            return new ResultTo(ResultEnum.OPERATION_FAILED, "更新失败");
        }
    }

    /**
     * 更新用户权限
     *
     * @return
     */
    @ReqPermission(type = PermissionType.GROUP_USER_PRIVILEGE, opt = PermissOpt.UPDATE)
    @PostMapping("/privilege")
    public ResultTo updatePrivilege(String id,
                                    @RequestParam(name = "authorization_code") String authorizationCode) {
        Example example = new Example(GlUser.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("id", id);
        GlUser user = new GlUser();
        if (StringUtils.isNotBlank(authorizationCode)) {
            user.setAuthorizationCode(authorizationCode.trim());
            user.setUpdateTime(new Date());
        }
        if (adaptService.updateByExampleSelective(user, example) == 1) {
            return new ResultTo(ResultEnum.SUCCESS, "更新成功");
        } else {
            return new ResultTo(ResultEnum.OPERATION_FAILED, "更新失败");
        }
    }

    /**
     * 删除人员
     *
     * @param id
     * @return
     */
    @ReqPermission(type = PermissionType.GROUP_USER, opt = PermissOpt.DELETE)
    @PostMapping("/remove")
    public ResultTo remove(String id) {
        Subject subject = SecurityUtils.getSubject();
        if (subject != null) {
            GlUser user = (GlUser) subject.getPrincipal();
            if (user.getId().equalsIgnoreCase(id)) {
                return new ResultTo(ResultEnum.OPERATION_FAILED, "删除失败，不能删除自己");
            }
        }
        if (DaoUtil.deleteById(adaptService, id, GlUser.class) == 1) {
            return new ResultTo(ResultEnum.SUCCESS, "删除成功");
        } else {
            return new ResultTo(ResultEnum.OPERATION_FAILED, "删除失败");
        }
    }
}
